<template>
  <div class="app-container">
    <!-- <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
</el-table-column>
<el-table-column label="Title">
  <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
</el-table-column>
<el-table-column label="Author" width="110" align="center">
  <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
</el-table-column>
<el-table-column label="Pageviews" width="110" align="center">
  <template slot-scope="scope">
          {{ scope.row.pageviews }}
        </template>
</el-table-column>
<el-table-column class-name="status-col" label="Status" width="110" align="center">
  <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag>
        </template>
</el-table-column>
<el-table-column align="center" prop="created_at" label="Display_time" width="200">
  <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.display_time }}</span>
        </template>
</el-table-column>
</el-table> -->
    <!--  功能区域 -->
    <el-form ref="form" :inline="true" :model="form" label-width="100px">
      <el-form-item label="实验室名">
        <el-input v-model="form.name" placeholder="请输入实验室名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="房间号">
        <el-input v-model="form.roomNumber" placeholder="请输入房间号" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item label="实验室类型">
        <el-select v-model="form.typeId" placeholder="选择实验室类型" clearable>
          <el-option v-for="(item, index) in laboratoryTypes" :key="item.id"
            :label="item.name + '——' + item.description" :value="item.id"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="实验室状态">
        <el-select v-model="form.status" placeholder="选择实验室状态" clearable>
          <el-option label="可用" value="AVAILABLE"></el-option>
          <!-- <el-option label="维护中" value="UNAVAILABLE"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-select v-model="form.enabled" placeholder="选择启用状态" clearable>
          <el-option label="启用" :value="true"></el-option>
          <el-option label="禁用" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="info" @click="handleReset">重置</el-button>
        <el-button type="success" @click="exportToExcel">导出当前页</el-button>
        <el-button type="warning" @click="exportAllToExcel">导出全部</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="list.content" style="width: 100%" element-loading-text="Loading" v-loading="listLoading" border>
      <!-- <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item :label="'开放时间段' + Number(index + 1)" v-for="(item, index) in scope.row.availableTimeSlots"
              :key="item.id">
              <span>{{ scope.row.availableTimeSlots[index].startTime | trimSeconds }} -- {{
                scope.row.availableTimeSlots[index].endTime | trimSeconds }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column> -->
      <el-table-column prop="name" label="实验室名" width="180">
      </el-table-column>
      <el-table-column prop="location" label="位置" width="180">
      </el-table-column>
      <el-table-column prop="roomNumber" label="门牌号">
      </el-table-column>
      <!-- <el-table-column label="图片">
        <template slot-scope="scope">
          <template v-for="(item, index) in scope.row.images">
            <img :src="item[index].url" alt="" style="width: 100px; height: 100px"></img>
          </template>
        </template>
      </el-table-column> -->
      <el-table-column label="开放时间">
        <template slot-scope="scope">
          <span>{{ scope.row.timeSlots | dayOf }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="examine(scope.$index, scope.row)">查看</el-button>
          <el-button type="primary" size="mini" @click="subscribe(scope.$index, scope.row)">预约</el-button>
          <!-- <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]" :page-size="pages.size" layout="total, sizes, prev, pager, next, jumper" :total="list.totalElements || 0">
    </el-pagination>

    <!-- 查看弹框1 -->
    <el-dialog title="实验室详细信息" :visible.sync="dialogVisible" width="60%">
      <div>{{ items.name }}</div>
      <div>{{ items.description }}</div>
      <div>{{ items.location }}-{{ items.roomNumber }}</div>
      <div>当前是否可用：{{ items.status == 'AVAILABLE' ? '是' : '否' }}</div>
      <div>当前是否开放预约：{{ items.isOpen? '是' : '否' }}</div>
      <div v-for="(item, index) in items.timeSlots" :key="item.id">实验室可预约时间：{{ item.dayOfWeek }} {{ item.startTime[0]
        }}点 - - {{ item.endTime[0] }}点 ---开放预约人数：{{ item.maxReservations }} 当前是否可预约{{ item.available == 'true' ? '是' :
        '否'
        }}</div>
      <div v-for="(item, index) in items.equipment" :key="item.id">实验室设备{{ item.name }} 型号：{{ item.model }} 设备简介{{
        item.description }} 数量{{ item.quantity }} </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>
    <!-- 预约弹框 -->
    <el-dialog title="预约实验室" :visible.sync="dialogVisible2" width="60%">
      <div>{{ items.name }}</div>
      <div>{{ items.description }}</div>
      <div>{{ items.location }}-{{ items.roomNumber }}</div>
      <div>当前是可用：{{ items.status == 'AVAILABLE' ? '是' : '否' }}</div>
      <div>当前是否开放预约：{{ items.isOpen? '是' : '否' }}</div>
      <!-- <div v-for="(item, index) in items.timeSlots" :key="item.id">实验室可预约时间：{{ item.dayOfWeek }} {{ item.startTime[0]
        }}点 - - {{ item.endTime[0] }}点 ---开放预约人数：{{ item.maxReservations }} 当前是否可预约{{ item.available == 'true' ? '是' :
        '否'
        }}</div>
      <div v-for="(item, index) in items.equipment" :key="item.id">实验室设备{{ item.name }} 型号：{{ item.model }} 设备简介{{
        item.description }} 数量{{ item.quantity }} </div> -->

      <!-- 表单 -->
      <el-form ref="form" :model="forms" label-width="140px">
        <el-form-item label="预约原因：">
          <el-input v-model="forms.purpose"></el-input>
        </el-form-item>
        <el-form-item label="预约用途：">
          <el-input v-model="forms.description"></el-input>
        </el-form-item>
        <el-form-item label="选择时间段：">
          <el-select v-model="forms.timeSlotId" placeholder="请选择活预约时间段" style="width: 100%">
            <el-option v-for="(item, index) in timerList" :key="item.id"
              :label="item.dayOfWeek + item.startTime[0] + '点-' + item.endTime[0] + '点'" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体日期：">
          <el-date-picker @change="breaktime" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
            v-model="forms.reservationDate" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="需要使用的设备：">
          <el-select v-model="forms.equipmentIds" placeholder="请选择活预约时间段" style="width: 100%">
            <el-option v-for="(item, index) in equipmentList" :key="item.id"
              :label="item.name + item.description + item.quantity + '台'" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="subscribet">预 约</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getEquipmentList, getTimerList, reservations, getlLaboratoriesTypes } from '@/api/table'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: { content: [] },
      listLoading: true,
      form: {
        name: '',
        roomNumber: '',
        typeId: '',
        status: '',
        enabled: ''
      },
      forms: {},
      currentPage: 1,
      pages: {
        page: 0,
        size: 10
      },
      dialogVisible: false,
      dialogVisible2: false,
      items: {},
      //设备列表
      equipmentList: [],
      //可预约时间段
      timerList: [],
      laboratoryTypes: []
    }
  },
  created() {
    this.fetchData()
    // 获取实验室类型数据
    this.fetchLaboratoryTypes()
  },
  filters: {
    trimSeconds(timeString) {
      // console.log(timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1'));
      if (!timeString) return '';
      return timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1');
    },
    // 相同的过滤
    dayOf(day) {
      // 遍历day，将day.dayOfWeek中相同的过滤掉只返回不同的
      let dayOfWeek = [];
      if (day.length === 0) return '';
      for (let i = 0; i < day.length; i++) {
        if (dayOfWeek.indexOf(day[i].dayOfWeek) === -1) {
          dayOfWeek.push(day[i].dayOfWeek);
        }
      }
      return dayOfWeek.join(',');
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      // 合并分页参数和查询参数
      const params = {
        ...this.pages,
        ...this.form
      };
      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });
      
      getList(params).then(response => {
        this.list = response.data
        this.listLoading = false
        console.log(this.list);
      }).catch(error => {
        this.listLoading = false
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败');
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pages.size = val;
      this.pages.page = 0; // 重置到第一页
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.pages.page = val - 1; // 后端从0开始，前端从1开始
      this.fetchData();
    },
    // 查看按钮
    examine(index, row) {
      this.dialogVisible = true;
      this.items = row;
      console.log(index, row);
    },
    // 预约按钮
    subscribe(index, row) {
      this.dialogVisible2 = true;
      this.forms.laboratoryId = row.id
      getEquipmentList(row.id).then(res => {
        this.equipmentList = res.data;
        console.log('实验室设备', res);
      })
      getTimerList(row.id).then(res => {
        this.timerList = res.data;
        console.log('可预约时间段', res.data);
      })
      this.items = row;
      console.log(index, row);
    },
    // 判断选中的事件与预约时间是否冲突
    breaktime(val){
      const date = new Date(val);
      console.log(date.getDay());
      const dayOfWeek = date.getDay();
      const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      const weekdayStr = weekdays[dayOfWeek];

      if (!this.forms.timeSlotId){
        this.$message.error('请先选择时间段');
        this.forms.reservationDate = '';
        return;
      }
      for (let i = 0; i < this.timerList.length; i++) {
        if (this.timerList[i].id === this.forms.timeSlotId) {
          if (this.timerList[i].dayOfWeek !== weekdayStr) {
            this.$message.error('所选时间段与日期不匹配');
            this.forms.reservationDate = '';
            return;
          }
      }
      
        
    }
  },
    // 预约
    subscribet() {
      console.log(this.forms);
      reservations(this.forms).then(res => {
        this.$message.success('预约成功');
        this.dialogVisible2 = false; // 关闭弹框
        this.fetchData(); // 刷新列表
        // 重置表单
        this.forms = {};
      }).catch(error => {
        console.error('预约失败:', error);
        this.$message.error('预约失败，请重试');
      });
    },
    handleSearch() {
      // 实现查询逻辑
      this.pages.page = 0;
      this.currentPage = 1;
      this.fetchData();
    },
    handleReset() {
      // 重置查询条件
      this.form = {
        name: '',
        roomNumber: '',
        typeId: '',
        status: '',
        enabled: ''
      };
      // 重置分页
      this.pages.page = 0;
      this.currentPage = 1;
      // 重新获取数据
      this.fetchData();
    },
    exportToExcel() {
      // 导出当前页Excel功能
      if (!this.list.content || this.list.content.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      // 准备导出数据
      const exportData = this.list.content.map(item => ({
        '实验室名称': item.name || '',
        '房间号': item.roomNumber || '',
        '位置': item.location || '',
        '容量': item.capacity || '',
        '类型': item.type ? item.type.name : '',
        '描述': item.description || '',
        '状态': item.status === 'AVAILABLE' ? '可用' : '不可用',
        '是否开放预约': item.isOpen ? '是' : '否'
      }));

      // 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      
      // 设置列宽
      const columnWidths = [
        { wch: 15 }, // 实验室名称
        { wch: 10 }, // 房间号
        { wch: 15 }, // 位置
        { wch: 10 }, // 容量
        { wch: 15 }, // 类型
        { wch: 30 }, // 描述
        { wch: 10 }, // 状态
        { wch: 15 }  // 是否开放预约
      ];
      worksheet['!cols'] = columnWidths;

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '实验室信息');

      // 生成文件名（包含当前时间）
      const now = new Date();
      const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
      const fileName = `实验室信息_${timestamp}.xlsx`;

      // 导出文件
      const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      FileSaver.saveAs(blob, fileName);

      this.$message.success('导出成功');
    },
    exportAllToExcel() {
      // 导出全部数据功能
      this.$confirm('确定要导出全部实验室信息吗？这可能需要一些时间。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportAllData();
      }).catch(() => {
        this.$message.info('已取消导出');
      });
    },
    async exportAllData() {
      try {
        this.$message.info('正在获取全部数据，请稍候...');
        
        // 获取所有数据（不分页）
        const allDataParams = {
          page: 0,
          size: 10000 // 设置一个很大的数字来获取所有数据
        };
        
        const response = await getList(allDataParams);
        const allData = response.data.content || [];
        
        if (allData.length === 0) {
          this.$message.warning('没有数据可导出');
          return;
        }

        // 准备导出数据
        const exportData = allData.map(item => ({
          '实验室名称': item.name || '',
          '房间号': item.roomNumber || '',
          '位置': item.location || '',
          '容量': item.capacity || '',
          '类型': item.type ? item.type.name : '',
          '描述': item.description || '',
          '状态': item.status === 'AVAILABLE' ? '可用' : '不可用',
          '是否开放预约': item.isOpen ? '是' : '否'
        }));

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        
        // 设置列宽
        const columnWidths = [
          { wch: 15 }, // 实验室名称
          { wch: 10 }, // 房间号
          { wch: 15 }, // 位置
          { wch: 10 }, // 容量
          { wch: 15 }, // 类型
          { wch: 30 }, // 描述
          { wch: 10 }, // 状态
          { wch: 15 }  // 是否开放预约
        ];
        worksheet['!cols'] = columnWidths;

        // 创建工作簿
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '全部实验室信息');

        // 生成文件名（包含当前时间）
        const now = new Date();
        const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
        const fileName = `全部实验室信息_${timestamp}.xlsx`;

        // 导出文件
        const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
        const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        FileSaver.saveAs(blob, fileName);

        this.$message.success(`导出成功，共导出 ${allData.length} 条记录`);
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      }
    },
    fetchLaboratoryTypes() {
      getlLaboratoriesTypes().then(response => {
        this.laboratoryTypes = response.data;
        console.log('实验室类型', response.data);
      });
    }
  }
}
</script>
